package com.mmall.util;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.mmall.Exception.ParamException;
import org.apache.commons.collections.MapUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.*;

/**
 * Created by pc on 2019/3/22.
 */
public class BeanBalidator {
    //全局校验工厂
    private static ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();

    public static <T>Map<String,String> validate(T t,Class... groups){
        //获取校验实例
        Validator validator = validatorFactory.getValidator();
        //开启校验
        Set validateResult = validator.validate(t,groups);
        if(validateResult.isEmpty()){
            return Collections.emptyMap();
        }else{
            LinkedHashMap errors = Maps.newLinkedHashMap();
           Iterator integer =  validateResult.iterator();
           while(integer.hasNext()){
               ConstraintViolation violation =(ConstraintViolation) integer.next();
               errors.put(violation.getPropertyPath().toString(),violation.getMessage());
           }
           return errors;
        }

    }

    public static Map<String,String> validateList(Collection<?> collection){
        Preconditions.checkNotNull(collection);
        Iterator integer = collection.iterator();
        Map errors;
        do{
            if(!integer.hasNext()){
                return Collections.emptyMap();
            }
            Object object = integer.next();
            errors = validate(object,new Class[0]);
        }while (errors.isEmpty());
        return errors;
    }


    public static Map<String,String> validateObject(Object first,Object... objects){
        if(objects != null && objects.length > 0){
            return validateList(Lists.asList(first,objects));
        }else {
            return validate(first,new Class[0]);
        }
    }

    /**
     * 抛出参数异常
     */
    public static void check(Object object)throws ParamException {
        Map<String,String> map = validateObject(object);
        if(MapUtils.isNotEmpty(map)){
            throw new ParamException(map.toString());
        }
    }
}
